
#include "stdafx.h"
#include "LPCSTRArray.h"

extern LPCSTR WideToLPSTR(LPCWSTR src, UINT codePage, intptr_t *pDestLen = nullptr);

CLPCSTRArray::CLPCSTRArray()
{
	count = 0; str = nullptr; maxLength = -1;
}

CLPCSTRArray::CLPCSTRArray(intptr_t initCount, intptr_t maxLen)
{
	if (initCount <= 0 || maxLen <= 0)
		CLPCSTRArray();
	else
	{
		count = initCount; maxLength = maxLen;
		intptr_t ncount = ((count + 15) >> 4) << 4;
		str = (LPCSTR*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, ncount*sizeof(LPCSTR));
		for (intptr_t i = 0; i < count; i++)
			str[i] = (LPCSTR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, maxLength);
	}
}

CLPCSTRArray::CLPCSTRArray(LPCSTR s, LPCSTR sepStr)
{
	count = 0; str = nullptr; maxLength = -1; build(s, sepStr);
}

CLPCSTRArray::CLPCSTRArray(LPCSTR s, char sepChar)
{
	count = 0; str = nullptr; maxLength = -1; build(s, sepChar);
}

CLPCSTRArray::CLPCSTRArray(LPCWSTR s, LPCSTR sepStr, UINT codePage)
{
	LPCSTR cs = WideToLPSTR(s, codePage);
	count = 0; str = nullptr; maxLength = -1; build(cs, sepStr);
	if (cs) HeapFree(GetProcessHeap(), 0, (LPVOID)cs);
}

CLPCSTRArray::~CLPCSTRArray()
{
	maxLength = -1; clear();
}

void CLPCSTRArray::buildW(LPCWSTR s, LPCSTR sepStr, UINT codePage)
{
	LPCSTR cs = WideToLPSTR(s, codePage);
	count = 0; str = nullptr; maxLength = -1; build(cs, sepStr);
	if (cs) HeapFree(GetProcessHeap(), 0, (LPVOID)cs);
}

LPCSTR CLPCSTRArray::find(LPCSTR p, char c)
{
	if (c) return strchr(p, c);
	if (p[0] == 0) return nullptr;
	if (p[0] & 0x80) p += 2; else p++;
	if (p[0] == 0) return nullptr;
	return p;
}

void CLPCSTRArray::makeLower()
{
	for (intptr_t i = 0; i < count; i++)
	{
		LPSTR v = (LPSTR)str[i];
		for (intptr_t j = 0; v[j]; j++) v[j] = tolower(v[j]);
	}
}



CLPCWSTRArray::CLPCWSTRArray()
{
	count = 0; str = nullptr; maxLength = -1;
}

CLPCWSTRArray::CLPCWSTRArray(LPCWSTR s, LPCWSTR sepStr)
{
	count = 0; str = nullptr; maxLength = -1; build(s, sepStr);
}

CLPCWSTRArray::CLPCWSTRArray(LPCWSTR s, char sepChar)
{
	count = 0; str = nullptr; maxLength = -1; build(s, sepChar);
}

CLPCWSTRArray::~CLPCWSTRArray()
{
	maxLength = -1; clear();
}

void CLPCWSTRArray::sort(bool desc)
{
	if (!str || count < 1) return;
	for (intptr_t i = 0; i < count - 1; i++) for (intptr_t j = i + 1; j < count; j++)
	{
		if (desc)
		{
			if (!str[i])
			{
				if (!str[j]) continue;
			}
			else if (!str[j])
				continue;
			if (wcscmp(str[i], str[j]) >= 0) continue;
		}
		else
		{
			if (!str[i])
				continue;
			else if (str[j])
			{
				if (wcscmp(str[i], str[j]) < 0) continue;
			}
		}
		LPCWSTR s = str[i]; str[i] = str[j]; str[j] = s;
	}
}
